import { defineStore } from 'pinia'
import { login, register, getCurrentUser, logout } from '@/services/auth'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null,
    token: localStorage.getItem('admin-token') || null,
    isAuthenticated: false,
    loading: false
  }),

  getters: {
    currentUser: (state) => state.user,
    isLoggedIn: (state) => state.isAuthenticated
  },

  actions: {
    // 登录
    async login(loginData) {
      this.loading = true
      try {
        const response = await login(loginData)
        this.token = response.token
        this.user = response.user
        this.isAuthenticated = true
        localStorage.setItem('admin-token', response.token)
        return response
      } catch (error) {
        throw error
      } finally {
        this.loading = false
      }
    },

    // 注册
    async register(registerData) {
      this.loading = true
      try {
        const response = await register(registerData)
        return response
      } catch (error) {
        throw error
      } finally {
        this.loading = false
      }
    },

    // 获取当前用户信息
    async fetchCurrentUser() {
      if (!this.token) return null
      
      try {
        const response = await getCurrentUser()
        this.user = response.user
        this.isAuthenticated = true
        return response.user
      } catch (error) {
        // 如果获取用户信息失败，清除认证状态
        this.logout()
        throw error
      }
    },

    // 登出
    async logout() {
      try {
        await logout()
      } catch (error) {
        console.error('Logout error:', error)
      } finally {
        this.user = null
        this.token = null
        this.isAuthenticated = false
        localStorage.removeItem('admin-token')
      }
    },

    // 初始化认证状态
    async initializeAuth() {
      if (this.token) {
        try {
          await this.fetchCurrentUser()
        } catch (error) {
          console.error('Failed to initialize auth:', error)
          this.logout()
        }
      }
    }
  }
})